from docx import Document
import xlsxwriter
from openpyxl import load_workbook
from openpyxl.styles import  Alignment

class WriteWordToExcel():

    def __init__(self,word_path,excelpath,sheetname):
        self.word_path = word_path
        self.excelpath = excelpath
        self.sheetname = sheetname


    def read_word(self):
        '''
        :return: 返回word中的文字，全在一个列表中，去除了空行
        '''
        doc = Document(self.word_path)
        #创建一个列表,把word里面所有的文字去除掉空行和前后空格添加到列表里面
        word_text_list = []
        for para in doc.paragraphs:
            word_text = para.text.strip()
            word_text = word_text.replace(" ","")
            if word_text == "":
                pass
            else:
                word_text_list.append(word_text)

        try:
            # 获取文档中表格信息
            tables = doc.tables  # 获取文档中所有表格对象的列表
            #只有一个表格，直接提取值
            tb = tables[0]
            # 获取表格的行
            tb_rows = tb.rows
            # 读取行内容
            row_cells = tb_rows[0].cells
            # 读取行单元格内容
            for cell in row_cells:
                # 单元格内容
                # print(cell.text)
                cell_text = cell.text.split('\n')
                for i in cell_text:
                    i = i.replace(" ","")
                    word_text_list.append(i)
            # print(word_text_list)

        except:
            # print("没获取到表格")
            pass

        del word_text_list[0]   #删除word中第一行的E-label information on device:




        return word_text_list

        # #每一段的编号、内容
        # for i in range(len(doc.paragraphs)):
        #     print(str(i),  doc.paragraphs[i].text)

    def word_msg_write_excel(self):
        word_text_list = self.read_word()
        word_msg = '\n'.join(word_text_list)
        workbook = xlsxwriter.Workbook(self.excelpath)
        sheet = workbook.add_worksheet(self.sheetname)

        format = {'align': 'center', 'valign': 'vcenter', 'text_wrap': 1}
        self.cell_format = workbook.add_format(format)  # 获取单元格属性

        # {'bold': True, 'font_size': 14, 'align': 'center','valign': 'vcenter','border':1,
        # 'color':'red', 'bg_color':'blue'}
        sheet.write(0, 0, "word_msg")  # 第一行，第一列
        sheet.write(0, 1, "tablet_msg")  # 第一行，第二列
        sheet.write(0,2,"result") #第一行，第三列
        sheet.write(0,3,"备注") #第一行，第四列
        sheet.write(1, 0, word_msg)  # 在第二行第一列写入word_msg
        sheet.set_column('A:A', 80, cell_format=self.cell_format)  # 设置A列宽度80
        sheet.set_column('B:B', 80, cell_format=self.cell_format)  # 设置B列宽度80
        sheet.set_column('D:D', 80, cell_format=self.cell_format)  # 设置D列宽度80
        # cell_format = workbook.add_format({'bold': True})
        sheet.set_row(0, 20, cell_format=self.cell_format)  # 设置第1行高度为300
        sheet.set_row(1, 300, cell_format=self.cell_format)  # 设置第2行高度为300
        workbook.close()

    def tablet_msg_write_excel(self,tablet_msg):
        #先读取完word里面的内容写到表格中
        self.word_msg_write_excel()
        # 写入已存在的xlsx文件
        wb = load_workbook(self.excelpath)  # 生成一个已存在的wookbook对象
        sheetname = self.sheetname
        wb1 = wb[sheetname]  # 写入指定的sheet
        # 设置B2中的数据垂直居中和水平居中以及自动换行
        wb1['B2'].alignment = Alignment(horizontal='center', vertical='center',wrap_text=1)
        wb1.cell(2,2,tablet_msg) #在第2行第2列写入table_msg
        wb.save(self.excelpath)
        wb.close()

    def wirte_result(self,result_msg):
        # 写入已存在的xlsx文件
        wb = load_workbook(self.excelpath)  # 生成一个已存在的wookbook对象
        sheetname = self.sheetname
        wb1 = wb[sheetname]  # 写入指定的sheet
        # 设置C1中的数据垂直居中和水平居中以及自动换行
        wb1['C2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=1)
        wb1.cell(2, 3, result_msg)  # 在第2行第3列写入result_msg
        wb.save(self.excelpath)
        wb.close()

    def wirte_backup(self,backup_msg):
        # 写入已存在的xlsx文件
        wb = load_workbook(self.excelpath)  # 生成一个已存在的wookbook对象
        sheetname = self.sheetname
        wb1 = wb[sheetname]  # 写入指定的sheet
        # 设置C1中的数据垂直居中和水平居中以及自动换行
        wb1['D2'].alignment = Alignment(horizontal='center', vertical='center', wrap_text=1)
        wb1.cell(2, 4, backup_msg)  # 在第2行第四列写入backup_msg
        wb.save(self.excelpath)
        wb.close()




    def change_word_format(self):
        ############把doc文件转化成docx文件
        from win32com import client as wc
        w = wc.Dispatch('Word.Application')
        # 或者使用下面的方法，使用启动独立的进程：
        # w = wc.DispatchEx('Word.Application')
        doc=w.Documents.Open("D:\Y_Script\imageContrast_1\wordFiles\\3_E-label Guide for Lenovo TB-J606F for ROW -删除页眉页脚.docx")
        doc.SaveAs("D:\Y_Script\imageContrast_1\E-label Guide for Lenovo TB-J606F for ROW123.docx",16)#必须有参数16，否则会出错

#
# if __name__ == '__main__':
#     Run = WriteWordToExcel(
#         "D:\Y_Script\\regulatory_labels\wordfiles\\3_E-label Guide for Lenovo TB-J606F for ROW -删除页眉页脚.docx",
#         "../excelfiles/excel_xlsx.xlsx", "labels_msg")
#     msg = Run.read_word()
#     print(msg)
# #     Run.word_msg_write_excel()